import { IRootReducerState } from '@/store/root-reducer';
import { IQueryParams } from '@/widgets/table-pagination';
import * as api from './user-api';
import { userSlice } from './user-slice';

const { actions } = userSlice;

export const setItem =
  (key: any) => async (dispatch: any, getState: () => IRootReducerState) => {
    const state = getState();
    const entityIdx = state.user.entities.findIndex(
      (e) => e[state.user.key] == key
    );
    if (entityIdx != -1) {
      dispatch(
        actions.entitySet({
          entity: state.user.entities[entityIdx],
          index: entityIdx,
        })
      );
    }
  };

export const nextItem =
  (curQueryParams?: IQueryParams) =>
  async (dispatch: any, getState: () => IRootReducerState) => {
    dispatch(actions.start());
    try {
      const state = getState();
      if (state.user.index + state.user.offset >= state.user.totalCount - 1) {
        return false;
      } else {
        // 本地获取下一个
        let nextEntityIdx = state.user.index + 1;
        let nextEntity = state.user.entities[nextEntityIdx];

        // 远程获取下一个
        if (!nextEntity && curQueryParams != null) {
          const newQueryParams = {
            ...curQueryParams,
            pageNum: state.user.offset + state.user.index + 2,
            pageSize: 1,
          };
          const response = await api.getList(newQueryParams);
          const {
            data: { list: items },
          } = response.data;
          if (items && items.length > 0) {
            nextEntityIdx = state.user.index + 1;
            nextEntity = items[0];
          }
        }
        if (nextEntityIdx != undefined && nextEntity) {
          dispatch(
            actions.entitySet({
              entity: nextEntity,
              index: nextEntityIdx,
            })
          );
          return nextEntity[state.user.key];
        } else {
          return null;
        }
      }
    } catch (err) {
      dispatch(actions.catchError(err));
    } finally {
      dispatch(actions.end());
    }
  };

export const prevItem =
  (curQueryParams?: IQueryParams) =>
  async (dispatch: any, getState: () => IRootReducerState) => {
    dispatch(actions.start());
    try {
      const state = getState();
      if (state.user.index + state.user.offset <= 0) {
        return false;
      } else {
        // 本地获取上一个
        let prevEntityIdx = state.user.index - 1;
        let prevEntity = state.user.entities[prevEntityIdx];

        // 远程获取上一个
        if (!prevEntity && curQueryParams != null) {
          const newQueryParams = {
            ...curQueryParams,
            pageNum: state.user.offset + state.user.index,
            pageSize: 1,
          };
          const response = await api.getList(newQueryParams);
          const {
            data: { list: items },
          } = response.data;
          if (items && items.length > 0) {
            prevEntityIdx = state.user.index - 1;
            prevEntity = items[0];
          }
        }

        if (prevEntityIdx != undefined && prevEntity) {
          dispatch(
            actions.entitySet({
              entity: prevEntity,
              index: prevEntityIdx,
            })
          );
          return prevEntity[state.user.key];
        } else {
          return null;
        }
      }
    } catch (err) {
      dispatch(actions.catchError(err));
    } finally {
      dispatch(actions.end());
    }
  };

export const fetchItems =
  (queryParams: IQueryParams) => async (dispatch: any) => {
    dispatch(actions.start());
    try {
      const response = await api.getList(queryParams);
      const { content: entities, totalElements: totalCount } = response.data;
      dispatch(
        actions.entitiesFetched({
          totalCount,
          entities,
          offset: (queryParams.pageNum - 1) * queryParams.pageSize,
        })
      );

      return entities;
    } catch (err) {
      dispatch(actions.catchError(err));
    }
  };

export const createItem = (entity: any) => async (dispatch: any) => {
  try {
    const response = await api.createItem(entity);
    return response;
  } catch (err) {
    dispatch(actions.catchError(err));
  }
};

export const updateItem = (entity: any) => async (dispatch: any) => {
  try {
    const response = await api.updateItem(entity);
    return response;
  } catch (err) {
    dispatch(actions.catchError(err));
  }
};
